#!/usr/bin/python3
# coding=utf-8

import time
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains


class ChromeHelper:
    def __init__(self, driver_path):
        self.chrome = webdriver.Chrome(executable_path=driver_path)

    def open(self, url):
        self.chrome.get(url)

    def close(self):
        """关闭当前打开的浏览器"""
        print("Browser is closed!")
        self.chrome.close()

    def quit(self):
        """关闭当前窗口,同时彻底退出webdriver，释放与driver server之间的连接。"""
        print("Browser is quit!")
        self.chrome.quit()

    def maximize_window(self):
        """窗口最大化"""
        self.chrome.maximize_window()

    def get_title(self, **kwargs):
        """获取当前页面的title 内容"""
        # curr_title = self.chrome.title()
        # curr_url = self.chrome.current_url()
        # curr_handler = self.chrome.current_window_handle
        return self.chrome.title()

    def search_element_show_by_xpath(self, browser, element):
        """查询目标元素是否存在, 返回True, False,以及这个元素对象
        :param browser: opened page
        :type browser: object
        :param element: target element in the browser
        :type element: page element with XPATH
        :return (True/False, Element/None)
        :rtype: tuple
        """
        flag = False
        locator = (By.XPATH, element)
        try:
            webObj = WebDriverWait(self.chrome, 60, 1).until(
                EC.visibility_of_element_located(locator)
            )
            flag = True
        except:
            webObj = None
        return (flag, webObj)


if __name__ == "__main__":
    driver_path = "./drivers/chromedriver.exe"
    chrome = ChromeHelper(driver_path)
    chrome.open("http://yapi.sunxing.net")
    chrome.maximize_window()
    xpath = '//*[@id="yapi"]/div/div[1]/div/div/div[1]/div[2]/div/div[2]/div[1]/div/div[3]/a'
    is_located, target_element = chrome.search_element_show_by_xpath(chrome, xpath)
    print(target_element)
    chrome.quit()
